package de.sonntagsfarben.puremvc.as3.modules.model
{
	import de.sonntagsfarben.puremvc.as3.modules.IModule;
	import de.sonntagsfarben.puremvc.as3.modules.ModuleLoader;
	import de.sonntagsfarben.puremvc.as3.modules.model.vo.ModuleVO;

	import org.puremvc.as3.multicore.interfaces.IProxy;
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;

	import flash.events.Event;
	import flash.events.IOErrorEvent;

	/**
	 * @author Soenke Kluth <sonntagsfarben.de>
	 */
	public class ModuleProxy extends Proxy implements IProxy
	{
		public static const LOAD_MODULE : String = NAME+'LOAD_MODULE';
		public static const UNLOAD_MODULE : String = NAME+'UNLOAD_MODULE';
		public static const MODULE_LOADED : String = NAME+'MODULE_LOADED';
		public static const MODULE_FAILED : String = NAME+'MODULE_FAILED';
		public static const MODULE_PROGRESS : String = NAME+'MODULE_PROGRESS';

		public static const NAME : String = "ModuleLoaderProxy";

		public function ModuleProxy( data : Array = null )
		{
			data = ( data ) ? data : new Array();
			super( NAME , data );
		}



		public function loadModule( moduleVo : ModuleVO ) : void
		{
			var loader : ModuleLoader = new ModuleLoader();
			loader.addEventListener( ModuleLoader.COMPLETE , onLoaded , false , 0 , true );
			loader.addEventListener( IOErrorEvent.IO_ERROR , onIOError , false , 0 , true );
			loader.load( moduleVo );
		}

		protected function onLoaded( event : Event ) : void
		{
			var moduleLoader : ModuleLoader = event.target as ModuleLoader;
			var module : IModule = moduleLoader.module;
			var moduleVO : ModuleVO = moduleLoader.moduleVO;

			sendNotification( MODULE_LOADED , module , moduleVO.name );
			removeListeners( moduleLoader );
		}

		protected function onIOError( event : IOErrorEvent ) : void
		{
			var moduleLoader : ModuleLoader = event.target as ModuleLoader;
			var module : IModule = moduleLoader.module;
			sendNotification( MODULE_FAILED , module , event.text );
			removeListeners( moduleLoader );
		}

		protected function removeListeners( moduleLoader : ModuleLoader ) : void
		{
			moduleLoader.removeEventListener( ModuleLoader.COMPLETE , onLoaded );
			moduleLoader.removeEventListener( IOErrorEvent.IO_ERROR , onIOError );
		}

		protected function onProgress( event : Event ) : void
		{
			var moduleLoader : ModuleLoader = event.target as ModuleLoader;
			sendNotification( MODULE_PROGRESS , moduleLoader.module );
		}

		public function get modules() : Array
		{
			return data as Array;
		}
	}
}

